<template>
  <view class="prescribing">
    <view class="tip">
      <image class="laba" :src="laba" />
      三定送药涉及药品均为处方药，仅实名购买并提供处方信息
    </view>
    <view class="cell-box">
      <view class="title">用药人</view>
      <view class="footer">
        {{ name }}<text v-if="real === '1'" class="terminal" style="margin: 0 0 0 24rpx">已实名</text>
      </view>
    </view>

    <view class="cells-box">
      <view class="top-title">请如实填写如下信息</view>

      <view v-for="item in domList" :key="item.type" class="cell-row">
        <view class="PMH">
          <view class="title">{{ item.title }}：</view>
          <view class="btn-group">
            <view :class="[item.radio === 0 ? 'cells-box-btn pitch' : 'cells-box-btn']" @click="radioChange(item, 0)">
              无<image class="curPostion" :src="curIcon" />
            </view>
            <view :class="[item.radio === 1 ? 'cells-box-btn pitch' : 'cells-box-btn']" @click="radioChange(item, 1)">
              有<image class="curPostion" :src="curIcon" />
            </view>
          </view>
        </view>
        <textarea
          v-if="item.radio === 1"
          class="cell-text"
          :maxlength="150"
          :placeholder="`请填写${item.title}情况`"
          @blur="bindTextAreaBlur($event, item)"
        />
      </view>
    </view>

    <view class="submit" @click="submit">免费复诊开方</view>
  </view>
</template>
<script>
/**
 * 在线复诊开方
 */
import { mapState } from 'vuex';
import curIcon from '@/static/icon/cur.png';
import laba from '@/static/icon/laba.png';
import { orderDrug, regularMedicationInfoEdit } from '@/api/drugInfo';

export default {
  data() {
    return {
      curIcon,
      laba,
      name: '',
      real: '',
      patientId: '',
      catalogId: '',
      domList: [
        { type: 'PMH', title: '过往病史', radio: undefined, remark: '' },
        { type: 'AMH', title: '过敏史', radio: undefined, remark: '' },
        { type: 'FMH', title: '家族病史', radio: undefined, remark: '' },
        {
          type: 'liverDesc',
          title: '肝功能异常',
          radio: undefined,
          remark: ''
        },
        {
          type: 'renalDesc',
          title: '肾功能异常',
          radio: undefined,
          remark: ''
        }
      ]
    };
  },

  computed: {
    ...mapState('assess', {
      drugs: (state) => {
        const qs = state.planDrugs.map((item) => {
          return {
            baseDrugId: item.baseDrugId,
            drugId: item.drugId,
            amount: item.amount,
            useAmount: item.useAmount,
            frequency: item.frequency
          };
        });
        return JSON.stringify(qs);
      },
      diseaseIds: 'diseaseIds',
      deliveryAddress: ({ addressInfo }) => {
        return {
          deliveryAddressType: 3, // 配送方式 1=居住地址 2=社区医院 3=自定义（1、3为配送，2为自提）
          deliveryRecipientName: addressInfo.name,
          deliveryRecipientContact: addressInfo.machineNumber,
          deliveryProvinceId: addressInfo.address.provinceId,
          deliveryCityId: addressInfo.address.cityId,
          deliveryAreaId: addressInfo.address.areaId,
          deliveryAddress: addressInfo.street,
          deliveryTime: '', // 配送日期
          id: addressInfo.id
        };
      },
      estimatedPickupDay: 'estimatedPickupDay',
      estimatedPickupPeriod: 'estimatedPickupPeriod',
      doctorId: 'doctorId'
    })
  },

  onLoad(opt) {
    // 姓名 + 是否实名 + 受益人ID + 药品目录ID
    if (opt) {
      this.name = decodeURIComponent(opt.name);
      this.real = opt.real;
      this.patientId = opt.patientId;
      this.catalogId = opt.catalogId;
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
    }
  },

  methods: {
    radioChange(item, val) {
      item.radio = val;
    },

    bindTextAreaBlur(e, item) {
      item.remark = e.detail.value;
    },

    async submit() {
      // 校验是否全部选择
      for (const item of this.domList) {
        if (item.radio === undefined) {
          uni.showToast({
            title: '有问题尚未回答,请填写后再次开方',
            icon: 'none'
          });
          return;
        }
        if (item.radio === 1 && !item.remark) {
          uni.showToast({
            title: `请填写 ${item.title} 病史情况后再次开方`,
            icon: 'none'
          });
          return;
        }
      }

      // 判断用户是否修改了配送日期, 以后是否沿用新日期
      if (this.estimatedPickupDay.setTime) {
        const _self = this;
        const initDay = this.estimatedPickupDay.initTime.split('-')[2];
        const setDay = this.estimatedPickupDay.setTime.split('-')[2];
        if (initDay !== setDay) {
          uni.showModal({
            content: '是否将今后的定期送日期时间调整为 ' + Number(setDay) + '日?',
            success: function (res) {
              if (res.confirm) {
                _self.deliveryAddress.deliveryTime = _self.estimatedPickupDay.setTime;
                _self.format();
              } else if (res.cancel) {
                _self.deliveryAddress.deliveryTime = _self.estimatedPickupDay.initTime;
                _self.format();
              }
            }
          });
        }
      } else {
        this.deliveryAddress.deliveryTime = this.estimatedPickupDay.initTime;
        this.format();
      }
    },

    async format() {
      uni.showLoading({
        title: '加载中...'
      });
      let electronicPrescription = {};
      this.domList.forEach((item) => {
        if (item.radio === 1) {
          electronicPrescription[item.type] = item.remark;
        } else {
          electronicPrescription[item.type] = '无';
        }
      });

      // 数据格式处理
      const data = {
        drugs: this.drugs, // 订购的药品列表
        diseasesIds: JSON.stringify(this.diseaseIds), // 疾病id数组
        deliveryAddress: JSON.stringify(this.deliveryAddress), // 配送地址
        period: this.estimatedPickupPeriod,
        prescribingSource: 3, // 处方开具来源 1=常规 2=电子处方 3=自有处方
        electronicPrescription: JSON.stringify(electronicPrescription),
        doctorId: this.doctorId,
        channel: 15, // 15项目(项目必填)
        catalogId: this.catalogId
      };
      await orderDrug(this.patientId, data)
        .then(async (res) => {
          if (res.code === 0) {
            const time = res.data.deliveryTime && res.data.deliveryTime.split(' ')[0];

            // 写入三定信息
            const data = {
              estimatedPickupPeriod: this.estimatedPickupPeriod,
              estimatedPickupDay: Number(this.deliveryAddress.deliveryTime.split('-')[2]),
              estimatedPickupDate: time,
              shippingAddress: JSON.stringify({
                id: this.deliveryAddress.id,
                name: this.deliveryAddress.deliveryRecipientName,
                machineNumber: this.deliveryAddress.deliveryRecipientContact,
                shippingAddressType: 3,
                provincesId: this.deliveryAddress.deliveryProvinceId,
                cityId: this.deliveryAddress.deliveryCityId,
                areaId: this.deliveryAddress.deliveryAreaId,
                street: this.deliveryAddress.deliveryAddress
              }),
              drugs: this.drugs
            };
            await regularMedicationInfoEdit(this.patientId, data);
            uni.hideLoading();
            this.$wxPromise.navigateTo({
              url: '/pages/registerResult/index?time=' + time
            });
          } else {
            uni.showToast({
              title: res.message,
              icon: 'none'
            });
          }
        })
        .catch((err) => {
          uni.hideLoading();
          console.log(err);
        });
    }
  }
};
</script>

<style lang="scss">
.prescribing {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  margin: 0 24rpx;
  .tip {
    font-size: 24rpx;
    color: #f34e1c;
    margin: 24rpx 0;
  }
  .laba {
    width: 32rpx;
    height: 32rpx;
    vertical-align: sub;
    margin-right: 12rpx;
  }

  .terminal {
    background: #fee9e9;
    font-size: 24rpx;
    padding: 8rpx 10rpx;
    border-radius: 8rpx;
    margin-right: 24rpx;
  }

  .cell-box {
    display: flex;
    justify-content: space-between;
    background: #ffffff;
    padding: 32rpx 24rpx;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    .title {
      color: rgba(0, 0, 0, 0.9);
    }
    .footer {
      font-size: 28rpx;
      color: rgba(0, 0, 0, 0.55);
    }
  }
  .cells-box {
    background: #ffffff;
    padding: 32rpx 24rpx;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    .title {
      color: rgba(0, 0, 0, 0.9);
      font-size: 32rpx;
    }
    &-btn {
      width: 176rpx;
      height: 72rpx;
      border-radius: 10px;
      border: 1px solid #b2b2b2;
      display: inline-block;
      line-height: 72rpx;
      text-align: center;
      .curPostion {
        display: none;
      }
    }
    .btn-group .cells-box-btn:last-child {
      margin-left: 48rpx;
    }
    .cell-text {
      width: 100%;
      border: 1px solid #e8e8e8;
      border-radius: 10px;
      height: 200rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin-top: 16rpx;
    }
  }
  .PMH {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .cell-row {
    margin: 40rpx 0;
  }
  .top-title {
    font-size: 36rpx;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.9);
  }
  .pitch {
    position: relative;
    border: 1px solid #f25559;
    .curPostion {
      width: 46rpx;
      height: 46rpx;
      position: absolute;
      bottom: 0;
      right: 0;
      display: block;
    }
    color: #f25559;
  }
  .submit {
    height: 88rpx;
    margin: 88rpx 0 60rpx;
    background: linear-gradient(236deg, #fe894d 0%, #ef3931 100%);
    font-size: 36rpx;
    color: #ffffff;
    line-height: 88rpx;
    text-align: center;
    border-radius: 44rpx;
  }
}
</style>
